# -*- coding:utf-8 -*-
import urllib.request
from http import cookiejar
import bs4
from urllib import parse
from bs4 import BeautifulSoup

account = input('请输入小写工号:')
psw = input('请输入密码:')
# 第一步登录考勤系统 保存cookie
result = urllib.request.urlopen("http://hr.koolearn-inc.com/login_.action")
soup = bs4.BeautifulSoup(result, "html.parser")

logindiv = soup.find("form", attrs={"class": "form-horizontal"})
Allinput = logindiv.findAll("input")
inputData = {}
for oneinput in Allinput:
    if oneinput.has_attr('name'):
        if oneinput.has_attr('value'):
            inputData[oneinput['name']] = oneinput['value']
        else:
            inputData[oneinput['name']] = ""
inputData['ssnEmail'] = account
inputData['psw'] = psw
inputData['yzm'] = 1
filename = 'cookie.txt'
# 声明一个MozillaCookieJar对象实例来保存cookie，之后写入文件
cookie = cookiejar.MozillaCookieJar(filename)
opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cookie))
postdata = urllib.parse.urlencode(inputData).encode(encoding='UTF8')
result2 = opener.open("http://hr.koolearn-inc.com/login_.action", postdata)
cookie.save(ignore_discard=True, ignore_expires=True)

# 第二步用之前的cookie访问考勤页面完成自动登录
bookUrl = "http://hr.koolearn-inc.com/login_index.action"
openRes = opener.open(bookUrl)
response = openRes.read().decode('utf-8')


#第三步解析考勤数据
data = BeautifulSoup(response, "html.parser")
table = data.find("table", attrs={"class": "table table-bordered table-striped table-hover table-condensed"})
trs = data.findAll("tr", attrs={"data-ssn": account})
print(trs)
dateList = [];
for tr in trs:
    _soup = BeautifulSoup(str(tr), "html.parser")
    tds = _soup.findAll(name='td')
    date = tds[0].string
    name = tds[3].string
    timeLength = float(tds[6].string)
    if (timeLength >= 1):
        dateList.append(date)

print()
print(' 你这个月总共加了 ' + str(dateList.__len__()) + ' 天班')
print("加班日期为:")
for date in dateList:
    print(date)
